<!-- 科目期初余额->客户往来 -->
<template>
    <div class="content-wrapper a-base-container">
        <div class="requisition-set-wrapper">
            <!-- 按钮 -->
            <div class="btn-wrapper clearfix">
                <a-row class="text-center clearfix">
                    <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                        <a-col v-if="permissions.includes('crmBalance:save')" :class="!editMask?'':'btns-disable'" :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="!editMask?handlerSubmit():''">
                                <a-icon class="btns-icon" type="save" />
                                <div class="btns-text">保存</div>
                            </div>
                        </a-col>
                        <a-col v-if="permissions.includes('crmBalance:edit')" :class="editMask?'':'btns-disable'" :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="editMask?handleEdit():''">
                                <a-icon class="btns-icon" type="edit" />
                                <div class="btns-text">修改</div>
                            </div>
                        </a-col>

                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="printOrder">
                                <a-icon class="btns-icon" type="printer" />
                                <div class="btns-text">打印</div>
                            </div>
                        </a-col>

                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="notExploit">
                                <a-icon class="btns-icon" type="audit" />
                                <div class="btns-text">记账</div>
                            </div>
                        </a-col>
                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="notExploit">
                                <a-icon class="btns-icon" type="audit" />
                                <div class="btns-text">取消记账</div>
                            </div>
                        </a-col>

                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="syncFun">
                                <a-icon class="btns-icon" type="sync" />
                                <div class="btns-text">刷新</div>
                            </div>
                        </a-col>
                    </a-col>
                </a-row>
            </div>
            <div ref="print" class="credentials-wrapper">
                <h3 class="text-center" style="width:1000px">
                    <span class="text-name">客户往来期初余额</span><br>
                </h3>
                <div class="bills-box-header-subjectsini">
                    <div class="filter">
                        <div class="filter-label">会计科目:</div>
                        <div class="filter-control">
                            <a-input @click="searchGroup(1)" @change="searchGroup(2)" v-model="name" autocomplete="off" placeholder="请选择科目名称">

                            </a-input>
                            <searchGroupHeader ref="credentialsSearch" :inputValue="name" :componentName="'accountingRadio'" @clickItem="setValue" :searchData="searchData"></searchGroupHeader>
                        </div>
                    </div>
                    <div class="filter">
                        <div class="filter-label">{{this.accountingName}}期初余额:</div>
                        <div class="filter-control" style="line-height:32px;">
                            {{initialBalance | NumFormat}}
                        </div>
                    </div>
                    <div class="filter">
                        <div class="filter-label">客户往来合计:</div>
                        <div class="filter-control" style="line-height:32px;">
                            {{totalInitialBalance | NumFormat}}
                        </div>
                    </div>
                    <div class="filter">
                        <div class="filter-label">平衡状态:</div>
                        <div class="filter-control" style="line-height:32px;">
                            平衡/不平衡
                        </div>
                    </div>
                </div>
                <section style="position:relative" v-show="showModel=='order'">
                    <a-row>
                        <a-col :span="24" style="width:1000px">
                            <div class="table-box margin-top-10">
                                <a-table id="credentials_tb" class="atable-edit" :columns="columns" :customRow="customClick" :data-source="dataSource" :pagination="false" bordered>
                                    <div v-for="item in editColumnArraya" :slot="item" slot-scope="text, record ,index" :key="item">
                                        <editable-cell v-if="isRouterAlive" :record="record" :col="item" :text="text" :dataSource="dataSource" @change="onCellChange(index, item, $event)" />
                                    </div>
                                </a-table>
                            </div>
                        </a-col>
                    </a-row>

                    <div class="edit-mask" style="width:100%;height:100%;" v-show="editMask">
                        <!-- 遮罩（点击修改关闭遮罩） -->
                    </div>
                </section>
            </div>
            <div class="contextmenu-box">
                <!-- 右键菜单 -->
                <ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
                    <li @click="handleAdd()">新增行</li>
                    <li @click="handleDelete()">删除行</li>
                </ul>
            </div>
        </div>

        <!--加载中-->
        <div class="loading-wrapper" v-show="loading">
            <a-spin class="loading-content" tip="加载中..." />
        </div>
        <!--用做横向打印-->
        <div v-html="stylePrint"></div>
    </div>
</template>
<script>

import { mapState } from "vuex";
import editableCell from "../accounting/editTable/EditableCell";

import { getAccountingBegin, saveAuxiliaryLedger, getAuxiList } from '@/api/finance/credentials';
import { save, getList, remove } from '@/api/finance/subjectsBalance';
import searchGroupHeader from "@/components/Finance/searchGroupHeader";
import FormSearchGroup from '@/components/Form/FormSearchGroup';
import moment from "moment";
import { getCurrencyDetailId } from "@/api/erp/currency";

export default {
    components: {
        editableCell,
        searchGroupHeader,
        FormSearchGroup,
    },
    // updated () {
    //     Controlwidth("credentials_tb", 50);
    // },
    data () {
        return {
            //----------↓样式----------
            btn_grid: {
                xs: 2,
                sm: 2,
                md: 2,
                lg: 2,
                xl: 2
            },
            formLayout: "inline",
            labelCol: { span: 10 },
            wrapperCol: { span: 14 },
            grid: {
                xs: 24,
                sm: 24,
                md: 12,
                lg: 8,
                xl: 8,
                xxl: 8
            },
            editMask: true,
            //----------↑样式----------
            beginDate: moment().format('YYYY-MM'),
            pagination: {
                current: 1,
                pageSize: 20,
                total: 0,
                size: 'small',
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input style="height:22px !important;width:3.2rem;"
                                value={this.pagination.pageSize}
                                min={1}
                                max={20}
                                size="small"
                                step={1}
                                onPressEnter={e => this.changePageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                onChange: (page, pageSize) => {
                    this.pagination.current = page;
                    this.getDataList();
                }
            },
            customClick: (record, index) => ({
                on: {
                    contextmenu: (e) => {//右键事件
                        e.preventDefault();
                        this.openMenu(e);
                        console.log('右键点击的', index);
                        this.thisClickId = index;
                    },
                    click: () => {
                        this.currentIndexTable = index;
                        console.log('当前点击的行下标', this.currentIndexTable)
                    }
                },
            }),
            searchText: null,
            thisClickId: null,
            showModel: 'order',//list:列表，order:单据
            columns: [{
                title: "客户首拼码",
                dataIndex: "phonetic",
                key: "phonetic",
                align: "left",
                scopedSlots: { customRender: 'phonetic' },
            },
            {
                title: "客户名称",
                dataIndex: "crmName",
                key: "crmName",
                align: "left",
                scopedSlots: { customRender: 'crmName' },
            },
            {
                title: '期初金额方向',
                dataIndex: 'beginAmountDirection',
                scopedSlots: { customRender: 'beginAmountDirection' },
                ellipsis: true,
            }, {
                title: '期初金额',
                dataIndex: 'beginAmount',
                scopedSlots: { customRender: 'beginAmount' },
                ellipsis: true,
            }],
            dataSource: [],
            visible: false,
            top: 0,
            left: 0,
            name: null,
            editColumnArraya: [],
            isRouterAlive: true,
            auxiliaryModal: false,//辅助计量弹窗是否显示
            voucherState: 0,    //审核状态
            invalidState: 0,    //作废状态
            voucherCode: 0,     //凭证编码  

            accountingCode: null,//科目编码
            accountingId: null,//科目id
            accountingName: null,//科目名称

            currentIndexTable: null,     //当前点击的行下标

            totalDebitAmount: null,  //借方金额合计
            totalCreditAmount: null,      //贷方金额合计

            currentId: null,     //当前凭证id
            currentCategoryArray: [],//当前凭证数组
            currentTitle: '凭证',
            calDirection: 1, //折算方式 1:原币*汇率=本位币 2:原币/汇率=本位币
            listDataSource: [],

            searchData: {//搜索条件
                isAuxaccCustomer: 1,//辅助中勾选客户往来的数据
                isEndNode: 1,//是否是末级
            },
            initialBalance: 0,//科目期初余额
            totalInitialBalance: 0,//科目辅助期初余额
        };
    },
    created () {
        this.editColumnArray(this.columns);

        // this.getDataList();
    },
    watch: {
        visible (value) {
            if (value) {
                document.body.addEventListener("click", this.closeMenu);
            } else {
                document.body.removeEventListener("click", this.closeMenu);
            }
        },
    },
    computed: {
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
        }),
    },
    methods: {
        moment,
        reload () {
            //强制刷新表格
            this.isRouterAlive = false;
            this.$nextTick(function () {
                this.isRouterAlive = true;
            });
        },
        printOrder () {
            //打印
            this.$print(this.$refs.print);
        },
        newPage () {
            this.showModel = 'order';
            this.editMask = false;
            this.voucherState = 0;
            this.invalidState = 0;
            this.dataJson = {
                vclassName: null,
                vclassId: null,
                // businessDate: moment().format('YYYY-MM-DD'),
            };

            this.dataSource = [];
            for (let i = 0; i < 10; i++) {
                let array = {}
                this.dataSource.push(array);
            }
            this.reload();
            this.clearTipsData();
        },
        onChangeBusinessDate (e, v) {
            //业务时间改变
            this.dataJson.businessDate = v;
        },
        openMenu (e) {
            //显示右键菜单
            var x = e.pageX - 250;
            var y = e.pageY - 40;
            this.top = y;
            this.left = x;
            this.visible = true;
        },
        closeMenu () {
            //隐藏右键菜单
            this.visible = false;
        },
        onCellChange (indexTable, dataIndex, value) {
            //当前点击的行下标
            this.currentIndexTable = indexTable;
            console.log('当前点击的数据：', value);
            if (!value) {
                return;
            }
            const dataSource = [...this.dataSource];
            const target = dataSource.find((item, index) => index === indexTable);
            if (dataIndex == 'crmName' || dataIndex == 'phonetic') {
                target['crmName'] = value.crmName;
                target['crmId'] = value.id;
                target['phonetic'] = value.phonetic;
                target['isEndNode'] = true;

            } else if (dataIndex == 'beginAmount') {
                //期初金额
                target[dataIndex] = value;

            } else {
                target[dataIndex] = value;
            }

            this.$nextTick(() => {
                this.totalInitialBalance = 0;
                dataSource.forEach(item => {
                    this.totalInitialBalance = Number(this.totalInitialBalance) + Number(item.beginAmount ? item.beginAmount : 0);
                });
                this.dataSource = dataSource;
                this.reload();
            })


        },
        getCurrencyDetailId (id) {
            getCurrencyDetailId({ id: id }).then(res => {
                if (res.code === 200) {
                    this.calDirection = res.data.calDirection;
                }
            })
        },
        clearTipsData () {
            //清空数据
            this.currentId = null;

            this.settleName = null;
            this.settleId = null;

            this.currencyBeginAmount = null;   //原币金额
            this.currencyId = null;       //币种id
            this.currencyName = null;    //币种名称
            this.exchangeRate = null;    //汇率
            this.debitAmountType = 1;     //借贷方向
            this.quantityBegin = null;        //数量
            this.price = null;           //单价
            this.unitId = null;          //计量单位id
            this.unitName = null;        //计量
        },
        onChangeDateDay (v, s) {
            this.billDate = s;
        },
        handleAdd () {
            //新增数据
            const { count, dataSource } = this;
            const newData = {};
            this.$nextTick(() => {
                this.dataSource.splice(this.dataSource.length, 0, newData);
            })
            console.log('新增行：', this.dataSource)
        },
        handleDelete () {
            //删除整行
            let _this = this;
            let numberId = this.thisClickId;
            console.log(numberId);
            this.$confirm({
                title: "确认",
                content: (
                    <span>
                        您确定要{<span style="color:red;">删除</span>}该记录吗？
                    </span>
                ),
                onOk () {
                    let dataSource = [..._this.dataSource];
                    console.log(_this.dataSource.length);
                    if (dataSource.length - 1 > 9) {
                        //大于规定行数(删除)
                        _this.dataSource = dataSource.filter((item, index) => index !== numberId);
                    } else {
                        //小于规定行数(清空)
                        for (let i = 0; i < dataSource.length; i++) {
                            if (i === numberId) {
                                for (const key in dataSource[i]) {
                                    if (key != 'number') {
                                        dataSource[i][key] = ""
                                    }
                                }
                            }
                        }
                        _this.dataSource = dataSource;
                    }
                    _this.reload();
                },
                onCancel () { },
            });
        },
        //获取可编辑的列名
        editColumnArray (column) {
            let editcloumn = [];
            column.forEach((item, index) => {
                editcloumn.push(item.dataIndex);
            });
            this.editColumnArraya = editcloumn;
        },
        searchGroup (t) {
            if (t == 1) {
                this.$refs.credentialsSearch.showModal();
            } else {
                //延迟请求
                if (this.setTime) {
                    clearTimeout(this.setTime)
                }
                this.setTime = setTimeout(() => {
                    this.$refs.credentialsSearch.inputSearch();
                }, 500)
            }
        },
        cancel () {
            this.auxiliaryModal = false;
        },
        handleSearch (n) {
            console.log(n);
            this.$refs[`${n}`].showModal();
        },
        setValue (data) {
            this.name = data.name;
            this.accountingCode = data.code;
            this.accountingId = data.id;
            this.accountingName = data.name;

            this.dataSource = [];
            //获取科目期初余额
            getAccountingBegin({ accountingId: data.id }).then(res => {
                if (res.code === 200) {
                    this.initialBalance = res.data ? res.data : 0;
                }
            })

            //获取数据
            this.getDataList();
        },

        handlerSubmit () {
            //提交数据
            let requestData = this.dataSource.filter(e => { return e.crmId });//表明细
            if (requestData.length < 1) {
                this.$message.warning('请输入明细表');
                return;
            }

            requestData.forEach(item => {
                item.accountingCode = this.accountingCode;
                item.accountingId = this.accountingId;
                item.accountingName = this.accountingName;
            });

            // if (this.initialBalance == 0 || this.totalInitialBalance == 0) {
            //     this.$message.warning('该会计科目未设置“科目期初余额”');
            //     return;
            // }
            // if (this.initialBalance != this.totalInitialBalance) {
            //     this.$message.warning('科目期初余额和当前往来期初余额不平衡');
            //     return;
            // }
            console.log('提交的数据：', requestData);

            const ids = requestData.map(item => item.crmId);
            const idsSet = new Set(ids);
            if (idsSet.size == ids.length) {
                console.log("不存在同个值")
            } else {
                console.log("存在同个值");
                this.$message.warning('期初设置不允许出现相同的客户！');
                return;
            }

            for (let i = 0; i < requestData.length; i++) {
                if (!requestData[i].beginAmountDirection) {
                    this.$message.warning(`第${i + 1}行：期初金额方向必须选择！`);
                    return;
                } else if (!requestData[i].beginAmount) {
                    this.$message.warning(`第${i + 1}行：期初金额必须填写！`);
                    return;
                }
            }

            saveAuxiliaryLedger(requestData).then(response => {
                if (response.code === 200) {
                    this.editMask = true;
                    this.voucherState = 0;

                    let that = this;
                    let success = `成功条数：${response.data.sCount}`;
                    let error = `失败条数：${response.data.fCount}`;
                    let msg = [];
                    for (let i = 0; i < response.data.result.length; i++) {
                        msg.push(<div>{response.data.result[i]}</div>);
                    }
                    let content = <div>
                        <span style="font-size:16px;color:green">{success}</span><br />
                        <span style="font-size:16px;color:red">{error}</span><br />
                        <div style="max-height:180px;overflow-y:auto;">{msg}</div>
                    </div>;
                    this.$confirm({
                        icon: () => { return <a-icon type="exclamation-circle" /> },
                        title: '操作结果',
                        content: content,
                        okText: '确定',
                        cancelText: '关闭',
                        footer: null,
                        onOk () {
                            that.getDataList();
                        },
                        onCancel () {
                            that.getDataList();
                        },
                    });
                } else {
                    // this.$message.warning(res.message);
                }
            }).catch(error => {

            })
        },
        getDataList (t) {
            //获取列表
            if (t == 'search') {
                this.pagination.current = 1;
            }
            let data = {
                accountingId: this.accountingId,
            };
            getAuxiList(data).then(res => {
                if (res.code === 200) {
                    this.dataSource = res.data.records;
                    this.totalInitialBalance = 0;
                    this.dataSource.forEach(item => {
                        this.totalInitialBalance += Number(item.beginAmount);
                    });

                    let len = this.dataSource.length;

                    if (len == 0) {
                        this.editMask = false;
                    }

                    for (let i = 0; i < 10 - len; i++) {
                        let array = {};
                        this.dataSource.push(array)
                    }

                    console.log(this.dataSource);

                    this.reload();
                    this.$forceUpdate();
                }
            })
        },
        handleRemove (type) {
            //type == 0 取消作废
            //type == 1 作废
            let that = this;
            this.$confirm({
                title: type == 1 ? `是否确认删除该数据？` : `是否确认恢复该数据？`,
                content: "",
                onOk () {
                    remove({ id: that.currentId, status: type }).then(res => {
                        if (res.code == 200) {
                            if (type == 1) {
                                that.$message.success("删除成功");
                            } else {
                                that.$message.success("恢复成功");
                            }
                            that.getDataList();
                            // that.getDataNewPage(5);
                        } else {
                            that.$message.warning(res.message);
                        }
                    })
                },
                onCancel () { }
            });
        },
        //修改
        handleEdit () {
            this.editMask = false;
        },
        //改变分页大小
        changePageSize (e) {
            const value = e.target.value;
            let size = Number.parseInt(value);
            if (!size) {
                size = 20;
            }
            if (size > 500) {
                size = 500;
            }
            const { pagination } = this;

            Object.assign(this.pagination, {
                current: 1,
                pageSize: size,
            });
            this.getDataList();
        },
        syncFun () {
            //刷新
            this.getDataList();
        },
        notExploit () {
            //暂未开发
            this.$message.warning('开发中...');
        }
    },

};
</script>
<style lang="less">
    @import '~@/style/purchase/voucher.less';
    .credentials-wrapper {
        padding: 10px;
        height: auto;
        overflow-y: auto;
        font-size: 14px;
        min-height: 350px;
        .date-tp {
            text-align: center;
            margin-bottom: 10px;
        }
        .footer-tp {
            text-align: center;
            margin-top: 10px;
        }

        .text-name {
            // border-bottom: 2px solid rgba(0, 0, 0, 0.8);
            padding-bottom: 5px;
        }
        .subsidiary {
            border: 1px solid #cacaca;
            text-align: center;
            display: flex;
            .sub-title {
                flex: 0 0 26px;
                padding-top: 8px;
                border-right: 1px solid #cacaca;
            }
            .sub-content {
                flex: 1;
                text-align: left;
                .sub-list {
                    border-bottom: 1px solid #cacaca;
                    line-height: 32px;
                    .ant-col {
                        padding-left: 20px;
                    }
                }
                .sub-list:last-child {
                    border-bottom: none;
                }
            }
        }
        .total-box {
            border-left: 1px solid #cacaca;
            border-right: 1px solid #cacaca;
            border-bottom: 1px solid #cacaca;
            display: flex;
            line-height: 32px;
            text-align: center;
            font-size: 14px;
            .total-title {
                width: 77.2%;
                border-right: 1px solid #cacaca;
                box-sizing: content-box;
            }
            .total-borrow {
                width: 11.4%;
                border-right: 1px solid #cacaca;
            }
            .total-loan {
                width: 11.4%;
            }
        }
        label:not(.form-check-label):not(.custom-file-label) {
            font-weight: normal;
        }
        .bills-box-header-subjectsini {
            display: flex;
            // justify-content: space-around;
            .filter {
                display: table;
                width: 246px;
                margin-bottom: 5px;
                .filter-label {
                    display: table-cell;
                    font-weight: normal;
                    max-width: 160px;
                    line-height: 32px;
                    white-space: nowrap;
                    vertical-align: bottom;
                    text-overflow: ellipsis;
                    overflow: hidden;
                }
                .filter-control {
                    display: table-cell;
                    width: 100%;
                }
            }
        }
    }

    .atable-edit {
        .ant-table-tbody > tr > td {
            padding: 0px 2px !important;
        }
    }

    //辅助弹窗
    .auxiliary-wapper {
        color: #222;
        .condition {
            padding: 0 10px;
            margin-bottom: 10px;
            overflow-y: auto;
            .filter {
                display: table;
                margin-top: 10px;
                .filter-label {
                    display: table-cell;
                    font-weight: normal;
                    max-width: 160px;
                    white-space: nowrap;
                    vertical-align: bottom;
                    text-overflow: ellipsis;
                    overflow: hidden;
                }
                .filter-control {
                    display: table-cell;
                    width: 100%;
                }
                .ant-select-selection--single {
                    height: auto;
                }
                .ant-input-number {
                    width: auto;
                }
                .ant-input,
                .ant-input-number,
                .ant-select-selection {
                    border-radius: 0;
                    border: none;
                    border-bottom: 1px solid #ccc;
                }
                .ant-input-number,
                .ant-select-selection,
                .ant-calendar-picker,
                .ant-calendar-picker-input,
                .ant-input:focus {
                    box-shadow: none;
                }
                .ant-input-number-handler-wrap {
                    display: none;
                }
                .ant-input-group-addon {
                    border: 0px;
                }
            }
        }
    }
</style>